<template>
  <!--  表格-->
  <el-table
      ref="auto-table"
      v-bind="$attrs"
      v-loading="loading"
      border stripe
      :data="tableData"
      style="width: 100%"
  >
    <el-table-column type="index" width="80" align="center" label="序号"/>
    <!--   默认内容-->
    <el-table-column
        v-for="(item,index) in columns"
        :key="`${item.prop}_${index}`"
        :show-overflow-tooltip="!item.tooltip"
        v-bind="item"
        align="center"
    >
      <template #header="scope" v-if="!!item.labelSlot">
        <slot :name="item.labelSlot" v-bind="scope"></slot>
      </template>
      <template #default="scope" v-if="!!item.tdSlot">
        <slot :name="item.tdSlot" v-bind="scope"></slot>
      </template>
    </el-table-column>
    <!--    插槽-->
  </el-table>
  <!-- 分页 -->
  <div class="page-box">
    <el-pagination
        v-if="paginationConfig.show"
        class="pagination"
        hide-on-single-page
        background
        :style="paginationConfig.style"
        @size-change="handleSizeChange"
        v-model:currentPage="pageNum"
        @current-change="handleCurrentChange"
        :page-sizes="paginationConfig.pageSizes"
        v-model:pageSize="pageSize"
        :layout="paginationConfig.layout"
        :total="total"
    ></el-pagination>
  </div>

</template>

<script>
// export default {
//   name: "AutoTable"
// }

import {defineComponent, reactive, toRefs, onBeforeMount} from "vue";

const formatDate = (date, format) => {
  let obj = {
    "M+": date.getMonth() + 1,
    "D+": date.getDate(),
    "H+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S+": date.getMilliseconds(),
  };
  if (/(y+)/i.test(format)) {
    format = format.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (let k in obj) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1
              ? obj[k]
              : ("00" + obj[k]).substr(("" + obj[k]).length)
      );
    }
  }
  return format;
};
const getSearchModel = (search) => {
  const searchModel = {};
  if (search && search.fields) {
    search.fields.forEach((item) => {
      switch (item.type) {
        case "checkbox":
        case "checkbox-button":
          searchModel[item.name] = [];
          break;
        default:
          break;
      }
      if (item.defaultValue !== undefined) {
        searchModel[item.name] = item.defaultValue;
        // 日期范围和时间范围真实变量默认值
        if (
            (item.type === "daterange" || item.type === "datetimerange") &&
            !!item.trueNames &&
            Array.isArray(item.defaultValue)
        ) {
          item.defaultValue.forEach((val, index) => {
            searchModel[item.trueNames[index]] = val;
          });
        }
      }
    });
  }
  return searchModel;
};

export default defineComponent({
  name: "AutoTable",
  props: {
    // 请求数据的方法
    request: {
      type: Function,
    },
    // 搜索表单配置，false表示不显示搜索表单
    search: {
      type: [Boolean, Object],
      default: false,
    },
    tableData: {
      type: Array,
      default: []
    },
    columns: {
      type: Array,
      default: () => []
    },
    // 分页配置，false表示不显示分页
    pagination: {
      type: [Boolean, Object],
      default: () => ({}),
    },
  },
  setup(props, {emit}) {
    // 优化搜索字段，
    // 1、如果搜索配置有transform处理函数，执行transform
    // 2、删除日期范围默认的name字段
    const optimizeFields = (search) => {
      const searchModel = JSON.parse(JSON.stringify(state.searchModel));
      if (search && search.fields) {
        search.fields.forEach((item) => {
          if (!searchModel.hasOwnProperty(item.name)) {
            return;
          }
          if (!!item.transform) {
            searchModel[item.name] = item.transform(searchModel[item.name]);
          }
          if (
              (item.type === "daterange" || item.type === "datetimerange") &&
              !!item.trueNames
          ) {
            delete searchModel[item.name];
          }
        });
      }
      return searchModel;
    };
    // 请求列表数据
    const getTableData = async () => {
      if(typeof props.request==='undefined') return
      state.loading = true;
      const searchModel = optimizeFields(props.search);
      const {data, total} = await props.request({
        pageNum: state.pageNum,
        pageSize: state.pageSize,
        ...searchModel,
      });
      state.loading = false;
      state.tableData = data;
      state.total = total;
    };
    onBeforeMount(() => {
      getTableData();
    });
    const state = reactive({
      searchModel: getSearchModel(props.search),
      loading: false,
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: (!!props.pagination && props.pagination.pageSize) || 10,
      paginationConfig: {
        show: false,
      },
      // 搜索
      // handleSearch() {
      //   state.pageNum = 1;
      //   getTableData();
      // },
      // 重置函数
      // handleReset() {
      //   if (JSON.stringify(state.searchModel) === "{}") {
      //     return;
      //   }
      //   state.pageNum = 1;
      //   state.searchModel = getSearchModel(props.search);
      //   getTableData();
      // },
      // 刷新
      refresh() {
        getTableData();
      },
      // 当前页变化
      handleCurrentChange(page) {
        getTableData();
      },
      // 改变每页size数量
      handleSizeChange(value) {
        state.pageNum = 1;
        getTableData();
      },
      // 全选
      // handleSelectionChange(arr) {
      //   emit("selectionChange", arr);
      // },
      // 过滤方法
      // filterHandler(value, row, column) {
      //   const property = column["property"];
      //   return row[property] === value;
      // },
      // 日期范围
      // handleDateChange(date, item, format) {
      //   state.searchModel[item.name] = !!date ? formatDate(date, format) : "";
      // },
      // handleRangeChange(date, item, format) {
      //   const arr = !!date && date.map((d) => formatDate(d, format));
      //   state.searchModel[item.name] = !!arr ? arr : [];
      //   if (!item.trueNames) {
      //     return;
      //   }
      //   if (!!arr) {
      //     arr.forEach((val, index) => {
      //       state.searchModel[item.trueNames[index]] = val;
      //     });
      //   } else {
      //     item.trueNames.forEach((key) => {
      //       delete state.searchModel[key];
      //     });
      //   }
      // },
    });
    if (typeof props.pagination === "object") {
      const {layout, pageSizes, style} = props.pagination;
      state.paginationConfig = {
        show: true,
        layout: layout || "total, sizes,  prev, pager, next, jumper",
        pageSizes: pageSizes || [10, 20, 30, 40, 50],
        style: style || {},
      };
    }
    return {
      ...toRefs(state),
    };
  },
})
</script>

<style lang="scss" scoped>
.page-box {
  display: flex;
  justify-content: right;
  align-items: center;
}
</style>
